<?php
namespace app\admin\controller;
use think\Input;
class Apporder extends Common{
    public function initialize(){
        parent::initialize();   
        $this->assign('shoplist',cache('shoplist'));   
        $this->assign('cionlist',cache('cionlist')); 
    }

    public function index(){
    	if(request()->isPost()){ 
            $where=[];
            $map='';
            $shopid = input('post.shopid');
            if($shopid) $where['shopid']=$shopid; 
            $timess = input('post.timess');            
            if($timess){ 
                $timess=explode(" - ",$timess);
                $starttime=strtotime($timess[0]);
                $endtime=strtotime($timess[1]);    
                $map= [$starttime,$endtime];  
            }
            $timequan = input('post.timequan');
            if($timequan) $map= ''.$timequan.''; 
            $orderid = input('post.orderid');
            if($orderid) $where['orderid']=$orderid;  
            $orderid_out = input('post.orderid_out');
            if($orderid_out) $where['orderid_out']=$orderid_out;   
            $state = input('post.state');
            if($state === "-1"){
                if($state)$where['state']="0";
            }else{
               if($state)$where['state']=$state; 
            }            
            $paytype = input('post.paytype');
            if($paytype)$where['paytype']=$paytype;  
               
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('apporder')
                ->where($where)->whereTime('addtime',$map)->order('id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();   
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                if($v['paytime']) $list['data'][$k]['paytime'] = date('Y-m-d H:i:s',$v['paytime']);
                if($v['state']===0){ 
                    $list['data'][$k]['state_name'] ='<span class="red">待支付</span>';
                }else if($v['state']===2){
                    $list['data'][$k]['state_name'] ='<span class="green">已确认</span>';
                }
                if($v['paytype']===1){ 
                    $list['data'][$k]['paytype'] ='<span class="blue">支付宝</span>';
                }else if($v['paytype']===2){
                    $list['data'][$k]['paytype'] ='<span class="green">微信</span>';
                }
                if($v['points']===0){
                    $list['data'][$k]['points_name'] ='<span class="orange">待上分</span>';
                }else if($v['points']===1){
                    $list['data'][$k]['points_name'] ='<span class="green">自动上分</span>';
                }else if($v['points']===2){
                    $list['data'][$k]['points_name'] ='<span class="green">手动上分</span>';
                }
                if($v['fei_user_jie']===0) $list['data'][$k]['fei_user']='<span class="orange" title="待结算">'.$v['fei_user'].'</span>';
                if($v['fei_shop_jie']===0) $list['data'][$k]['fei_shop']='<span class="orange" title="待结算">'.$v['fei_shop'].'</span>';
                if($v['fei_agent_jie']===0) $list['data'][$k]['fei_agent']='<span class="orange" title="待结算">'.$v['fei_agent'].'</span>';
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        } 
        $shoplist=cache('shoplist');
        if(!$shoplist){
            $shoplist=db('shop')->where('open',1)->order('id')->select();
            cache('shoplist',$shoplist);
        }
        $this->assign('title','APP订单管理');
        return $this->fetch();

    } 
    
    public function total(){
        if(request()->isPost()){ 
            $where=[];
            $map='';
            $shopid = input('post.shopid');
            if($shopid) $where['shopid']=$shopid; 
            $timess = input('post.timess');            
            if($timess){ 
                $timess=explode(" - ",$timess);
                $starttime=strtotime($timess[0]);
                $endtime=strtotime($timess[1]);
                if($starttime >= $endtime){
                    return $result = ['code'=>-1,'msg'=>'开始时间要早于结束时间!','rel'=>1];    
                } 
                $map= [$starttime,$endtime];  
            }
            $timequan = input('post.timequan');
            if($timequan) $map= ''.$timequan.''; 
            $orderid = input('post.orderid');
            if($orderid) $where['orderid']=$orderid;  
            $orderid_out = input('post.orderid_out');
            if($orderid_out) $where['orderid_out']=$orderid_out;   
            $state = input('post.state');
            if($state === "-1"){
                if($state)$where['state']="0";
            }else{
               if($state)$where['state']=$state; 
            }            
            $paytype = input('post.paytype');
            if($paytype)$where['paytype']=$paytype;
            $s_today=strtotime(date('Y-m-d'),time());   
            $e_today=strtotime(date('Y-m-d'),time())+86399;
            $maps=[$s_today,$e_today];
            $payorder=[];
            $payorder['no']=db('apporder')->where('state',0)->where($where)->whereTime('addtime',$map)->sum('money');
            $payorder['yes']=db('apporder')->where('state',2)->where($where)->whereTime('addtime',$map)->sum('money'); 
            $payorder['num']=count(db('apporder')->where('state',2)->where($where)->whereTime('addtime',$map)->select()); 

            $payorder['today_total']=db('apporder')->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('money');
            $payorder['today_feishop']=db('apporder')->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('fei_shop'); 
            $payorder['today_shop']=$payorder['total_money']-$payorder['total_feishop'];
            $payorder['today_num']=count(db('apporder')->where('state',2)->where($where)->whereTime('addtime',$maps)->select());
            $payorders[0]=$payorder;
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$payorders,'rel'=>1];
        } 
    }

    // public function settle(){
    //     if(request()->isPost()){ 
    //         // $where=[];
    //         // $map='';
    //         // $shopid = input('post.shopid');
    //         // if($shopid) $where['shopid']=$shopid; 
    //         // $timess = input('post.timess');            
    //         // if($timess){ 
    //         //     $timess=explode(" - ",$timess);
    //         //     $starttime=strtotime($timess[0]);
    //         //     $endtime=strtotime($timess[1])+86399;    
    //         //     $map= [$starttime,$endtime];  
    //         // }
    //         // $timequan = input('post.timequan');
    //         // if($timequan) $map= ''.$timequan.''; 
    //         // $orderid = input('post.orderid');
    //         // if($orderid) $where['orderid']=$orderid;  
    //         // $orderid_out = input('post.orderid_out');
    //         // if($orderid_out) $where['orderid_out']=$orderid_out;   
    //         // $userid = input('post.userid');
    //         // if($userid) $where['o.userid']=$userid;  
    //         // $channelid = input('post.channelid');
    //         // if($channelid) $where['o.channelid']=$channelid;  
    //         // $agentid = input('post.agentid');
    //         // if($agentid) $where['o.agentid']=$agentid;  

    //         // $state = input('post.state');
    //         // if($state === "-1"){
    //         //     if($state)$where['state']="0";
    //         // }else{
    //         //    if($state)$where['state']=$state; 
    //         // }
            
    //         // $points = input('post.points');
    //         // if($points)$where['points']=$points;

    //         // $paytype = input('post.paytype');
    //         // if($paytype)$where['ub.name_en']=$paytype;  
               
    //         $page =input('page')?input('page'):1;
    //         $pageSize =input('limit')?input('limit'):config('pageSize');
    //         $list=db('settle')
    //             // ->where($where)->whereTime('time',$map)->order('state desc')
    //             ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
    //             ->toArray();
    //         foreach ($list['data'] as $k=>$v){
    //             $list['data'][$k]['time'] = date('Y-m-d H:i:s',$v['time']);
    //             // if($v['paytime']) $list['data'][$k]['paytime'] = date('Y-m-d H:i',$v['paytime']);
    //             // if($v['state']===0){ 
    //             //     $list['data'][$k]['state_name'] ='<span class="red">待支付</span>';
    //             // }else if($v['state']===1){
    //             //     $list['data'][$k]['state_name'] ='<span class="blue">待确认</span>';
    //             // }else if($v['state']===2){
    //             //     $list['data'][$k]['state_name'] ='<span class="green">已确认</span>';
    //             // }else if($v['state']===3){
    //             //     $list['data'][$k]['state_name'] ='<span class="hui">已取消</span>';
    //             // }else if($v['state']===-1){
    //             //     $list['data'][$k]['state_name'] ='<span class="hui">已删除</span>';
    //             // } 
    //             // if($v['points']===0){
    //             //     $list['data'][$k]['points_name'] ='<span class="orange">待上分</span>';
    //             // }else if($v['points']===1){
    //             //     $list['data'][$k]['points_name'] ='<span class="green">自动上分</span>';
    //             // }else if($v['points']===2){
    //             //     $list['data'][$k]['points_name'] ='<span class="green">手动上分</span>';
    //             // }
    //             // if($v['fei_user_jie']===0) $list['data'][$k]['fei_user']='<span class="orange" title="待结算">'.$v['fei_user'].'</span>';
    //             // if($v['fei_shop_jie']===0) $list['data'][$k]['fei_shop']='<span class="orange" title="待结算">'.$v['fei_shop'].'</span>';
    //             // if($v['fei_agent_jie']===0) $list['data'][$k]['fei_agent']='<span class="orange" title="待结算">'.$v['fei_agent'].'</span>';
    //         }

    //         return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
    //     } 
    //     $shoplist=cache('shoplist');
    //     if(!$shoplist){
    //         $shoplist=db('shop')->where('open',1)->order('id')->select();
    //         cache('shoplist',$shoplist);
    //     }
    //     $this->assign('title','APP订单管理');
    //     return $this->fetch();
    // }

    public function settlelist()
    {
        if(request()->isPost()){ 
            $where=[];
            $map='';
            $shopid = input('post.shopid');
            if($shopid){
                $where['shopid']=$shopid;
            }else{
               return $result = ['code'=>2,'msg'=>'请选择商户结算'];
            } 
            $timess = input('post.timess');            
            if($timess){ 
                $timess=explode(" - ",$timess);
                $starttime=strtotime($timess[0]);
                $endtime=strtotime($timess[1]);    
                $map= [$starttime,$endtime];  
            }
            $timequan = input('post.timequan');
            if($timequan) $map= ''.$timequan.''; 
            $orderid = input('post.orderid');
            if($orderid) $where['a.orderid']=$orderid;  
            $orderid_out = input('post.orderid_out');
            if($orderid_out) $where['a.orderid_out']=$orderid_out;              
            $list=db('apporder')
                    ->alias('a')
                    ->join(config('database.prefix') . 'shop s', 'a.shopid = s.id', 'left')
                    ->where(array('state' =>2,'fei_shop_jie'=>0))
                    ->where($where)
                    ->whereTime('a.addtime',$map)
                    ->select(); 
            if($list){

                //支付宝
                $alist=db('apporder')->where(array('paytype' =>1))->where(array('state' =>2,'fei_shop_jie'=>0))->where($where)->whereTime('addtime',$map)->select();   
                if($alist){
                    foreach ($alist as $ak => $av) {
                        $amoney += $av['money'];
                    }
                }else{
                    $amoney=0;
                }

                //微信
                $wlist=db('apporder')->where(array('paytype' =>2))->where(array('state' =>2,'fei_shop_jie'=>0))->where($where)->whereTime('addtime',$map)->select();
                if($wlist){
                    foreach ($alist as $wk => $wv) {
                        $wmoney += $wv['money'];
                    }
                }else{
                    $wmoney = 0;
                }

                foreach ($list as $k=>$v){                     
                    $money += $v['money'];
                    db('apporder')->where('id',$v['id'])->update(['fei_shop_jie'=>1,'fei_shop_time'=>time()]);
                }
                $lvstr=$list[0]['lv'];
                $lv=explode('|', $lvstr);
                // var_dump($list);die;
                $data = array(
                    'orderid' => 'J'.rand_string(8,1).'S'.$shopid, 
                    'type_name' => '商户', 
                    'total_money' => $money, 
                    'amoney' => $amoney, 
                    'wmoney' => $wmoney,
                    'wxlv' =>  $lv[0],
                    'alv' =>  $lv[1], 
                    'payshop' => $amoney*(1-$lv[1]*0.01)+$wmoney*(1-$lv[0]*0.01), 
                    'income' => $money-$amoney*(1-$lv[1]*0.01)+$wmoney*(1-$lv[0]*0.01), 
                    'sname' => $list[0]['shopname'], 
                    'uname' => $list[0]['username'], 
                    'moblie' => $list[0]['mobile'], 
                    'time' => time(), 
                ); 
                db('settle')->insertGetId($data);
                return $result = ['code'=>1,'msg'=>'结算结束'];
            }else{
               return $result = ['code'=>0,'msg'=>'无需结算']; 
            }
        }else{
           return $result = ['code'=>-1,'msg'=>'请联系管理员']; 
        }
    }


     //新订单结算
    public function settle(){
        if(request()->isPost()){ 
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('settle')->alias('j')
                ->join(config('database.prefix') . 'users u', 'j.userid = u.id', 'left')
                ->join(config('database.prefix') . 'shop s', 'j.shopid = s.id', 'left')
                ->field('j.*,u.mobile,s.mobile as smobile,s.username as susername')
                ->order('j.addtime desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))->toArray(); 
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:i',$v['addtime']);
                if($v['type']=='user'){
                    $list['data'][$k]['typename']='码商'; 
                    $list['data'][$k]['shopname']=$v['username']; 
                }else if($v['type']=='agent'){
                    $list['data'][$k]['typename']='代理'; 
                    $list['data'][$k]['shopname']=$v['username']; 
                }else if($v['type']=='shop'){
                    $list['data'][$k]['typename']='商户'; 
                    $list['data'][$k]['username']=$v['susername']; 
                    $list['data'][$k]['mobile']=$v['smobile']; 
                }
                if($v['state']===0){
                    if($v['type']=='user'){
                        $list['data'][$k]['money_sf']=$v['money_a']-$v['money_s'];
                        $list['data'][$k]['money_sf']='<span class="green">+'.$list['data'][$k]['money_sf'].'</span>'; 
                    }else if($v['type']=='shop'){
                        $list['data'][$k]['money_sf']=$v['money_a']-$v['money_s'];
                        $list['data'][$k]['money_sf']='<span class="red">-'.$list['data'][$k]['money_sf'].'</span>'; 
                    }else if($v['type']=='agent'){
                        $list['data'][$k]['money_sf']='<span class="red">-'.$v['money_s'].'</span>'; 
                    }
                    $list['data'][$k]['state_name']='<span class="red">待处理</span>'; 
                }else{
                    if($v['type']=='user'){
                        $list['data'][$k]['money_sf']=$v['money_a']-$v['money_s'];
                        $list['data'][$k]['money_sf']='+'.$list['data'][$k]['money_sf']; 
                    }else if($v['type']=='shop'){
                        $list['data'][$k]['money_sf']=$v['money_a']-$v['money_s'];
                        $list['data'][$k]['money_sf']='-'.$list['data'][$k]['money_sf']; 
                    }else if($v['type']=='agent'){
                        $list['data'][$k]['money_sf']='-'.$v['money_s']; 
                    }
                    $list['data'][$k]['state_name']='<span class="green">已处理</span>'; 
                }
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        if(!$shoplist){
            $shoplist=db('shop')->where('open',1)->order('id')->select();
            cache('shoplist',$shoplist);
        }
        return $this->fetch();
    }


    public function handle_settle(){
        if(request()->isPost()){
            $where=[];
            $map='';
            $shopid = input('post.shopid');
            if($shopid){
                $where['shopid']=$shopid; 
            }else{
                return $result = ['code'=>-1,'msg'=>'请选择商户!','rel'=>1];
            } 
            $timess = input('post.timess');
            if($timess){ 
                $timess=explode(" - ",$timess);
                $starttime=strtotime($timess[0]);
                $endtime=strtotime($timess[1]); 
                if($starttime >= $endtime){
                    return $result = ['code'=>-1,'msg'=>'开始日期要早于结束日期!','rel'=>1]; 
                } 
                //2019-05-17 13:36:53 - 2019-05-17 13:37:48  
                $map= [$starttime,$endtime];  
            }
            $orderid = input('post.orderid');
            if($orderid) $wheres['orderid']=$orderid;  
            $orderid_out = input('post.orderid_out');
            if($orderid_out) $wheres['orderid_out']=$orderid_out;  

            $list_shop=db('apporder')
                            ->where(array('state' =>2,'fei_shop_jie' =>0))
                            ->whereTime('addtime',$map)
                            ->where($where)
                            ->where($wheres)
                            ->order('id desc')
                            ->select();
            // $list_agent=db('apporder')
            //                 ->where(array('state' =>2,'fei_agent_jie' =>0))
            //                 ->whereTime('addtime',$map)
            //                 ->where($where)
            //                 ->where($wheres)
            //                 ->group('agentid')
            //                 ->select();
            // $list_user=db('apporder')
            //                 ->where(array('state' =>2,'fei_user_jie' =>0))
            //                 ->whereTime('addtime',$map)
            //                 ->where($where)
            //                 ->where($wheres)
            //                 ->group('userid')
            //                 ->select();

            if(!empty($list_shop)){
                if($list_shop){
                        $money_s[$k]=0;
                        $money_a[$k]=0;
                        $number[$k]=0;
                        foreach ($list_shop as $kk=>$vv){
                            $money_s[$k] +=$vv['fei_shop'];
                            $money_a[$k] +=$vv['money'];
                            $number[$k] +=1;
                            db('apporder')->where('id',$vv['id'])->update(['fei_shop_jie'=>1,'fei_shop_time'=>time()]); 
                        } 
                        $datas[$k]= array(
                            'orderid' =>'J'.rand_string(8,1).'S'.$v['shopid'], 
                            'money_s' =>$money_s[$k], 
                            'money_a' =>$money_a[$k], 
                            'number' =>$number[$k], 
                            'state' =>0, 
                            'type' =>'shop', 
                            'shopid' =>$vv['shopid'], 
                            'shopname' =>$vv['shopname'], 
                            'addtime' =>time(), 
                        );
                        db('settle')->insertGetId($datas[$k]);
                }

                // if($list_agent){
                //     foreach ($list_user as $k=>$v){ 
                //         $order_user=db('apporder')->where(array('state' =>2,'fei_agent_jie' =>0,'agentid'=>$v['agentid']))->whereTime('addtime',$map)->where($where)->where($wheres)->select(); 
                //         $money_s[$k]=0;
                //         $money_a[$k]=0;
                //         $number[$k]=0;
                //         foreach ($order_user as $kk=>$vv){
                //             $money_s[$k] +=$vv['fei_agent'];
                //             $money_a[$k] +=$vv['money'];
                //             $number[$k] +=1;
                //             db('apporder')->where('id',$vv['id'])->update(['fei_agent_jie'=>0,'fei_agent_time'=>time()]);
                //         } 
                //         if($v['agentid']){
                //             $username[$k]=db('users')->where('id',$v['agentid'])->value('username');
                //             $datas[$k]= array(
                //                 'orderid' =>'J'.rand_string(8,1).'S'.$v['agentid'], 
                //                 'money_s' =>$money_s[$k], 
                //                 'money_a' =>$money_a[$k], 
                //                 'number' =>$number[$k], 
                //                 'state' =>0, 
                //                 'type' =>'agent', 
                //                 'userid' =>$v['agentid'], 
                //                 'username' =>$username[$k], 
                //                 'addtime' =>time(), 
                //             ); 
                //             db('settle')->insertGetId($datas[$k]);
                //         } 
                //     }
                    
                // }
                
                // if($list_user){
                //     foreach ($list_user as $k=>$v){ 
                //         $order_user=db('apporder')->where(array('state' =>2,'fei_user_jie' =>0,'userid'=>$v['userid']))->whereTime('addtime',$map)->where($where)->where($wheres)->select(); 
                //         $money_s[$k]=0;
                //         $money_a[$k]=0;
                //         $number[$k]=0;
                //         foreach ($order_user as $kk=>$vv){
                //             $money_s[$k] +=$vv['fei_user'];
                //             $money_a[$k] +=$vv['money'];
                //             $number[$k] +=1;
                //             db('apporder')->where('id',$vv['id'])->update(['fei_user_jie'=>0,'fei_user_time'=>time()]);
                //         } 
                //         $username[$k]=db('users')->where('id',$v['userid'])->value('username');
                //         $datas[$k]= array(
                //             'orderid' =>'J'.rand_string(8,1).'S'.$v['userid'], 
                //             'money_s' =>$money_s[$k], 
                //             'money_a' =>$money_a[$k], 
                //             'number' =>$number[$k], 
                //             'state' =>0, 
                //             'type' =>'user', 
                //             'userid' =>$v['userid'], 
                //             'username' =>$username[$k], 
                //             'addtime' =>time(), 
                //         ); 
                //         db('settle')->insertGetId($datas[$k]);
                //     }
                // }
                return $result = ['code'=>1,'msg'=>'结算完成!','rel'=>1]; 
            }else{
                return $result = ['code'=>0,'msg'=>'无需结算!','rel'=>1]; 
            }    
        }else{
            return $result = ['code'=>-1,'msg'=>'请正确操作!','rel'=>1]; 
        }
       
       
    } 

     public function pass_jiesuan(){
        if(request()->isPost()){  
            if(db('settle')->where(array('id'=>input('id'),'state'=>0))->update(['state'=>1])!==false){
                return ['code'=>1,'msg'=>'操作成功！'];
            }else{
                return ['code'=>-1,'msg'=>'操作失败！'];
            } 
        }
    }   

}